/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * cadastroRaca.java
 *
 * Created on 29/09/2009, 21:24:26
 */

package cparc;

import cparc.*;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;



public class cadastroRaca extends javax.swing.JInternalFrame {
    boolean alterar = false;
    boolean cadastrar = false;
    static String nomeUser = null;

    /** Creates new form cadastroRaca */
    public cadastroRaca(String user) {
        initComponents();

        nomeUser = user;

        tfCodRac.enable(false);
        tfNomRac.enable(false);

        DefaultTableModel modelo = (DefaultTableModel) tbRac.getModel();
        Statement stm = null;
        String result = null;
        String consulta = "select rcod, rnom from cparc.cad_racas ORDER BY RNOM ASC";
        int i=0;

        try  {
        stm = (Statement) conexao.getConnection(true).createStatement();
        ResultSet rs = stm.executeQuery(consulta);

        while(rs.next()){
        modelo.addRow(new String[] {Integer.toString(rs.getInt("rcod")), rs.getString("rnom")});
        modelo.fireTableCellUpdated(i, 0);
        modelo.fireTableCellUpdated(i, 1);
        i++;
        }

        }
        catch(Exception e){
            String status = e.getMessage();
            System.out.println(status);
        }
        }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        btConsultar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbRac = new javax.swing.JTable();
        label2 = new java.awt.Label();
        label1 = new java.awt.Label();
        jSeparator1 = new javax.swing.JSeparator();
        tfCodRac = new javax.swing.JTextField();
        tfNomRac = new javax.swing.JTextField();
        tfCon = new javax.swing.JTextField();

        setClosable(true);
        setTitle("Cadastro de Raças");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jButton2.setText("Alterar");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jButton2MouseReleased(evt);
            }
        });
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Salvar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton4.setText("Excluir");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton3.setText("Cadastrar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        btConsultar.setText("Consultar");
        btConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConsultarActionPerformed(evt);
            }
        });

        tbRac.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código da Raça", "Nome da Raça"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbRac.getTableHeader().setReorderingAllowed(false);
        tbRac.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbRacMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbRac);

        label2.setText("Raça");

        label1.setText("Código da Raça");

        tfCon.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfConKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(94, 94, 94)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)))
                .addContainerGap(95, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(tfCon, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btConsultar, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18))
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfCodRac, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfNomRac, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(30, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(tfCodRac)
                    .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfNomRac, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
                    .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btConsultar)
                    .addComponent(tfCon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(27, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        tfCon.setText("Digite a raça para consultar...");
        tfCon.requestFocusInWindow();
        tfCon.selectAll();
        alterar = true;
        cadastrar = false;
}//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (cadastrar)
        {
        Statement stm = null;
        String result = null;
        String cadastrar = "INSERT INTO CPARC.CAD_RACAS (RCOD,RNOM) VALUES(\"" + tfCodRac.getText() + "\", \"" + tfNomRac.getText().toUpperCase() + "\")";
        String valores = tfCodRac.getText() +","+ tfNomRac.getText().toUpperCase();
        log log_raca = new log("raca_insert", nomeUser, valores, cadastrar);

        try  {
        stm = (Statement) conexao.getConnection(true).createStatement();
        int rs = stm.executeUpdate(cadastrar);

        }
        catch(Exception e){
            String status = e.getMessage();
            System.out.println(status);
        }

        }

        if (alterar)
        {
             Statement stm = null;
        String result = null;
        String cadastrar = "update cparc.cad_racas set rnom = \"" + tfNomRac.getText()+ "\" where rcod = " + tfCodRac.getText();
        String valores = tfCodRac.getText()+","+tfNomRac.getText();
        log log_raca = new log("raca_update", nomeUser, valores, cadastrar);

        try  {
        stm = (Statement) conexao.getConnection(true).createStatement();
        int rs = stm.executeUpdate(cadastrar);

        }
        catch(Exception e){
            String status = e.getMessage();
            System.out.println(status);
        }

        }
        tfCon.setText("");
        btConsultar.doClick();
        tfCodRac.setEnabled(false);
        tfNomRac.setEnabled(false);
        alterar = false;
        cadastrar = false;
}//GEN-LAST:event_jButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed

        Statement stm = null;
        String result = null;
        String excluir = "delete from cparc.cad_racas where rcod = " + tfCodRac.getText();
        String valores = tfCodRac.getText() + "," + tfNomRac.getText();
        int n;

       Object[] options = { "Confirmar", "Cancelar" };
       n = JOptionPane.showOptionDialog(null, "Você está prestes a excluir a raça: " + tfNomRac.getText() + "!\n Realizar a exclusão?", "Operação de exclusão!", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
       
       if(n == 0)
       {
       try  {
        stm = (Statement) conexao.getConnection(true).createStatement();
        int rs = stm.executeUpdate(excluir);
        log log_raca = new log("raca_delete", nomeUser, valores, excluir);
        }
        catch(Exception e){
            String status = e.getMessage();
            System.out.println(status);
        }
       }
       tfCon.setText("");
       btConsultar.doClick();
}//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    alterar = false;
    cadastrar = true;

    DefaultTableModel modelo = (DefaultTableModel) tbRac.getModel();
        Statement stm = null;
        String result = null;
        String consulta = "select rcod from cparc.cad_racas" ;
        int ncod = 0;

        try  {
        stm = (Statement) conexao.getConnection(true).createStatement();
        ResultSet rs = stm.executeQuery(consulta);

        while(rs.next()){
            int cod = Integer.parseInt(rs.getString("rcod"));
            if (cod > ncod)
                ncod = cod;
        }
        }
        catch(Exception e){
            String status = e.getMessage();
            System.out.println(status);
        }

        tfCodRac.setEnabled(true);
        tfNomRac.setEnabled(true);
        tfCodRac.setText(String.valueOf(ncod + 1));
        tfNomRac.setText("");
        tfNomRac.requestFocusInWindow();

}//GEN-LAST:event_jButton3ActionPerformed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown

    }//GEN-LAST:event_formComponentShown

    private void jButton2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseReleased

    }//GEN-LAST:event_jButton2MouseReleased

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked

    }//GEN-LAST:event_jButton2MouseClicked

    private void tbRacMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbRacMouseClicked
        int line = tbRac.getSelectedRow();
        String cod = (String) tbRac.getValueAt(line, 0);
        tfCodRac.setText(cod);
        String nom = (String) tbRac.getValueAt(line, 1);
        tfNomRac.setText(nom);

        if(alterar)
        {
        tfNomRac.enable(true);
        tfNomRac.requestFocusInWindow();
        tfNomRac.selectAll();
        }
    }//GEN-LAST:event_tbRacMouseClicked

    private void btConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConsultarActionPerformed
        DefaultTableModel modelo = (DefaultTableModel) tbRac.getModel();
        modelo.setRowCount(0);
        Statement stm = null;
        String result = null;
        String consulta = "select rcod, rnom from cparc.cad_racas where rnom like \"%" + tfCon.getText() + "%\" order by rnom asc" ;
        int i=0;
        try  {
        stm = (Statement) conexao.getConnection(true).createStatement();
        ResultSet rs = stm.executeQuery(consulta);
        rs.afterLast();
        while(rs.previous()){
        modelo.addRow(new String[] {Integer.toString(rs.getInt("rcod")), rs.getString("rnom")});
        modelo.fireTableCellUpdated(i, 0);
        modelo.fireTableCellUpdated(i, 1);
        i++;
        }
        }
        catch(Exception e){
            String status = e.getMessage();
            System.out.println(status);
        }
    }//GEN-LAST:event_btConsultarActionPerformed

    private void tfConKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfConKeyPressed
        if(evt.getKeyCode()== 10)
        {
            btConsultar.doClick();
            tfCon.requestFocusInWindow();
            tfCon.selectAll();
        }
    }//GEN-LAST:event_tfConKeyPressed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btConsultar;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private java.awt.Label label1;
    private java.awt.Label label2;
    private javax.swing.JTable tbRac;
    private javax.swing.JTextField tfCodRac;
    private javax.swing.JTextField tfCon;
    private javax.swing.JTextField tfNomRac;
    // End of variables declaration//GEN-END:variables

}
